<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Validator;
use App\User;
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }


    public function wxLogin(Request $request){
        $oauth_user = session('wechat.oauth_user'); // 拿到授权用户资料
        //dd($request->all());
        //寻找openid字段如果没有找到跳转到登录页面提示绑定
        $user = User::where('openid', $oauth_user->getId())->first();
        if($oauth_user->getId() && $user){
            auth()->login($user, true);
            //$this->login($request);
            //return $this->sendLoginResponse($request);
            //$targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
            //header('location:'. $targetUrl); // 跳转到 user/profile

            return redirect()->back();
            //return redirect('/login');
        }else{
            $validator = Validator::make($request->all(),[]);
            $validator->after(function($validator) {

                $validator->errors()->add('mobile', '使用账号登录自动绑定微信号!');
                
            });

            return redirect('/login')->withErrors($validator)->withInput();;
        }
    }
}
